//
//  RegisteredAccountVC.m
//  DataStatistics
//
//  Created by Kang on 16/1/4.
//  Copyright © 2016年 YTYangK. All rights reserved.
//

#import "RegisteredAccountVC.h"
#import "YJLocalCountryData.h"
#import "PhoneNumber.h"
#import <AddressBook/AddressBook.h> //通讯录
#import <SMS_SDK/SMSSDK.h>
#import "SectionsViewController.h"
#import "UIView+RGSize.h"
#import "NetRequestClass.h"
#import <IQKeyboardManager.h>
#import "UtilToolsClass.h"
#import "ACWebviewViewController.h"
#import "UtilToolsClass.h"
#define LABEL ((MLLinkLabel*)self.Continue)
@interface RegisteredAccountVC () <UITextFieldDelegate, UIAlertViewDelegate,UIGestureRecognizerDelegate,SectionsViewControllerDelegate> {
    // 默认View 的Frame
    CGRect frameDefault;
    // 记录是否点击
    BOOL isClick;
    int second;
    UIAlertController* alert;
    // 容器
    UIToolbar* topview;
    //  获取到请求的值
    int resultInt;
}
@property (strong, nonatomic) UIButton *eliminateContent;
@property (retain, nonatomic) NSTimer* timer;
@property (assign, nonatomic, setter=isSuccessful:) BOOL whetherSuccess;
@end

@implementation RegisteredAccountVC

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.btnSMS.enabled = NO;
    [self updateUI];
    [self.btnSMS setTitle:NSLocalizedString(@"下一步", nil) forState:UIControlStateNormal];
    self.iphoneNum.placeholder = NSLocalizedString(@"电话号码", nil);
    self.areaName.text = NSLocalizedString(@"中国", nil);
    [IQKeyboardManager sharedManager].enableAutoToolbar = YES;
    
    UIBarButtonItem* backIetm = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"back@3x"] style:UIBarButtonItemStylePlain target:self action:@selector(backItemClick)];
    self.navigationItem.leftBarButtonItem = backIetm;
    self.navigationItem.hidesBackButton = YES;  
}

-(void)backItemClick{
    [self.navigationController popViewControllerAnimated:YES];
}


- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.iphoneNum.delegate = self;
    [self.navigationController setNavigationBarHidden:NO animated:YES];
    
}


#pragma mark - 设置内容
- (void)updateUI
{
    // 设置地区按钮的右边的箭头图标
    [self.clickAreaBtn setImage:[UIImage imageNamed:@"icon-goto"] forState:UIControlStateNormal];
    frameDefault = self.view.frame;

    [self.view addSubview:[self eliminateContent]];
    [self.iphoneNum addTarget:self action:@selector(textLengthMethod:) forControlEvents:UIControlEventEditingChanged];
    if ([self.RAVCsignStr isEqualToString:@"Forget"]) {
        self.viceGuideLabel.hidden = YES;
        self.Continue.hidden = YES;
        [self updateForgetUI];
    }
    else if ([self.RAVCsignStr isEqualToString:@"Registered"]) {
        self.viceGuideLabel.height = NO;
        self.Continue.hidden = NO;
        [self updateRegisteredUI];
    }
}


#pragma mark  更新 注册UI
- (void)updateRegisteredUI
{
    self.title = NSLocalizedString(@"注册", nil);
    self.guideLabel.text = [NSString stringWithFormat:@"%@?",NSLocalizedString(@"您的号码是什么", nil)];
    self.viceGuideLabel.text = [NSString stringWithFormat:@"%@.",NSLocalizedString(@"不要担心,我们永远不会公开显示它", nil)];

    if (!self.Continue.hidden) {
        // 段落样式
        NSMutableParagraphStyle* paragraph = [[NSMutableParagraphStyle alloc] init];
        //指定段落
        paragraph.firstLineHeadIndent = 2;
        //调整文字缩进像素
        paragraph.headIndent = 13;

        // 下划线 + 字体
        NSMutableAttributedString* attrStr = [[NSMutableAttributedString alloc] initWithString:NSLocalizedString(@"REGIST-CONTINUE", nil)];
        // 1 表示的是中文
        if ([UtilToolsClass judgeLocalLanguage] == 1) {
            [attrStr addAttribute:NSLinkAttributeName value:@"http://www.oilklenze.com.cn/ac/terms_of_use.html" range:NSMakeRange(13, 4)];
            [attrStr addAttribute:NSLinkAttributeName value:@"http://www.oilklenze.com.cn/ac/privacy_policy.html" range:NSMakeRange(26, 4)];
        }else{
            [attrStr addAttribute:NSLinkAttributeName value:@"http://www.oilklenze.com.cn/ac/terms_of_use.html" range:NSMakeRange(29, 12)];
            [attrStr addAttribute:NSLinkAttributeName value:@"http://www.oilklenze.com.cn/ac/privacy_policy.html" range:NSMakeRange(69, 14)];
        }

        self.Continue.attributedText = attrStr;
        self.Continue.font = [UIFont systemFontOfSize:14.f];
        self.Continue.textAlignment = NSTextAlignmentLeft;
        self.Continue.textInsets = UIEdgeInsetsMake(-5, 5, 5, 5);
        self.Continue.lineHeightMultiple = 0.9f;
        self.Continue.beforeAddLinkBlock = nil;
        self.Continue.dataDetectorTypes = MLDataDetectorTypeAll;
        self.Continue.allowLineBreakInsideLinks = YES;
        self.Continue.linkTextAttributes = nil;
        self.Continue.activeLinkTextAttributes = nil;
        __weak typeof(self) weakSelf = self;
        [self.Continue setDidClickLinkBlock:^(MLLink* link, NSString* linkText, MLLinkLabel* label) {
              if ([linkText isEqualToString:@"Privacy Policy"]) {
                [weakSelf gotoWebView:linkText linkUrl:link.linkValue];
            }
            else {
                   [weakSelf gotoWebView:linkText linkUrl:link.linkValue];
            }
        }];
        // 小橙点
        UIView* smartV = [[UIView alloc] initWithFrame:CGRectMake(CGRectGetMinX(self.Continue.frame) - 10, self.Continue.origin.y - self.Continue.size.height * 0.5 - 10, 6, 6)];
        smartV.backgroundColor = [UIColor orangeColor];
        smartV.layer.cornerRadius = 4.0f;
        [self.view addSubview:smartV];
    }
}


#pragma mark  更新 忘记密码UI
- (void)updateForgetUI{
    self.title = NSLocalizedString(@"请输入您的手机号码", nil);
    self.guideLabel.text = NSLocalizedString(@"FORGET-PASSWORD-GUID", nil);
    self.guideLabel.font = [UIFont systemFontOfSize:13.f];
}


/** 跳转协议 */
- (void)gotoWebView:(NSString*)keyStr  linkUrl:(NSString *) url
{
    ACWebviewViewController* web = [[ACWebviewViewController alloc] init];
    web.title = keyStr;
    web.url = url;
    web.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:web animated:YES];
    
}


// 限制长度
- (void)textLengthMethod:(UITextField*)textField{
    if (textField == self.iphoneNum) {
        // 长度限制
        if (self.iphoneNum.text.length > 11) {
            self.iphoneNum.text =  [self.iphoneNum.text substringToIndex:11];
             self.btnSMS.enabled = YES;
        }
        // 中国区域的手机号码做一个格式判断
        if ([self.areaCode.text isEqualToString:@"+86"]) {
            if ([PhoneNumber isMobileNumber:textField.text] == NO){
                self.btnSMS.enabled = NO;
            }else{
                self.btnSMS.enabled = YES;
            }

        }
     }
}


#pragma mark - TextField Delegate
- (BOOL)textFieldShouldReturn:(UITextField*)textField
{
  
    return YES;
}



#pragma mark 校验手机
- (IBAction)clickSMSPinCodeBtn:(id)sender
{
    [self.view endEditing:YES];

    [self resignRespondersForText];
    
    self.btnSMS.enabled = NO;
    UIAlertAction* cancelAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"取消", nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        self.btnSMS.enabled = YES;
    }];
    UIAlertAction* okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"确定", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction* _Nonnull action) {
        if (resultInt == 1) {
            if ([self.areaCode.text isEqualToString:@"+86"]) {

                if ([PhoneNumber isMobileNumber:_iphoneNum.text] == NO) {
                    [self resignRespondersForText];
                    [UtilToolsClass addDisapperAlert:NSLocalizedString(@"", nil) withMessage:NSLocalizedString(@"请输入符合格式的手机号码", nil)];
                }
                else {
                    [self SMSSDK];
                }
            }
            else {
                [self SMSSDK];
            }
        }
        else {
            if (resultInt == 2) {
                if ([_RAVCsignStr isEqualToString:@"Forget"]) {
                    [self SMSSDK];
                }
            }
        }

    }];

    [[UtilToolsClass getUtilTools] addDoLoading];
    NSString* str2 = [self.areaCode.text stringByReplacingOccurrencesOfString:@"+" withString:@""];
    [NetRequestClass requestWithUrlForCheckPhoneNumber:self andUrl:[NSString stringWithFormat:@"%@userInfo/phoneVerify.asp",REQUESTHEADER] andParam:@{@"loginName":_iphoneNum.text,@"zone":str2} success:^(NSInteger result) {
        [[UtilToolsClass getUtilTools] removeDoLoading];
        resultInt = (int)result;
        // 1 未注册
        if (result == 1) {
            if ([_RAVCsignStr isEqualToString:@"Registered"]) {
                NSString* str = [NSString stringWithFormat:@"%@:%@ %@",NSLocalizedString(@"REGIST-PHONENUMBER", nil) , self.areaCode.text, self.iphoneNum.text];
                [UtilToolsClass addViewController:self withTitleStr:NSLocalizedString(@"确认手机号码", nil) withMessage:str withAction:cancelAction withOKAction:okAction withStyle:UIAlertControllerStyleAlert];
            }
            else {
                   // 找回密码
                [UtilToolsClass addDisapperAlert:NSLocalizedString(@"", nil) withMessage:NSLocalizedString(@"FORGET-PASSWORD", nil)];
                self.btnSMS.enabled = YES;
            }
        }
        // 已注册
        if (resultInt == 2) {
            if ([_RAVCsignStr isEqualToString:@"Forget"]) {
                NSString* str = [NSString stringWithFormat:@"%@:%@ %@", NSLocalizedString(@"REGIST-PHONENUMBER", nil), self.areaCode.text, self.iphoneNum.text];
                [UtilToolsClass addViewController:self withTitleStr:NSLocalizedString(@"确认手机号码", nil) withMessage:str withAction:cancelAction withOKAction:okAction withStyle:UIAlertControllerStyleAlert];
            }
            else {
                [UtilToolsClass addDisapperAlert:NSLocalizedString(@"", nil) withMessage:NSLocalizedString(@"VERIFICATION-JUDGE-NUMBER", nil)];
                self.btnSMS.enabled = YES;
            }
        }
        // 出现异常
        if (resultInt == 0)
        {
            [UtilToolsClass addDisapperAlert:NSLocalizedString(@"", nil) withMessage:NSLocalizedString(@"A system exception", nil)];
            self.btnSMS.enabled = YES;
        }
  
    } failure:^(NSString *error) {
        self.btnSMS.enabled = YES;
        [[UtilToolsClass getUtilTools] removeDoLoading];
        [UtilToolsClass addDisapperAlert:NSLocalizedString(@"", nil) withMessage:error];
    }];
    
}



#pragma mark SMSSDK获取验证码
- (void)SMSSDK
{
        NSString* str2 = [self.areaCode.text stringByReplacingOccurrencesOfString:@"+" withString:@""];
        [SMSSDK getVerificationCodeByMethod:SMSGetCodeMethodSMS phoneNumber:self.iphoneNum.text zone:str2 customIdentifier:nil result:^(NSError *error) {
            if (!error) {
                NSLog(@"获取验证码成功");
            if ([self.RAVCsignStr isEqualToString:@"Forget"]) {}
                [self performSegueWithIdentifier:@"RegisteredVerification" sender:self];
            }else{
                NSLog(@"error :%@",error.userInfo);
                NSString *messageStr = [NSString stringWithFormat:@"%@",error.userInfo[@"getVerificationCode"]];
                self.btnSMS.enabled = YES;
               if (error.code == 461) {
                      [UtilToolsClass addDisapperAlert:@"" withMessage:NSLocalizedString(@"不支持该地区发送短信", nil)];
               }else{
                   if(error.code == 477){
                           [UtilToolsClass addDisapperAlert:@"" withMessage:NSLocalizedString(@"PHONENUMBER-LIMIT", nil)];
                   }else{
                            [UtilToolsClass addDisapperAlert:@"" withMessage:NSLocalizedString(messageStr, nil)];
                   }
               }
            }
        }];
}


//传值
- (void)prepareForSegue:(UIStoryboardSegue*)segue sender:(id)sender
{
    NSString* str2 = [self.areaCode.text stringByReplacingOccurrencesOfString:@"+" withString:@""];

    if ([segue.identifier compare:@"RegisteredVerification"] == NO) {

        id vc = segue.destinationViewController;
        [vc setValue:_RAVCsignStr forKey:@"VVCsignStr"];
        [vc setValue:_iphoneNum.text forKey:@"VVC_phoneNumber"];
        [vc setValue:str2 forKey:@"VVC_areaNam"];
        [vc setValue:_window forKey:@"VVC_window"];
    }
}

#pragma mark - resign responders
- (void)resignRespondersForText{
        if (SYSTEM_VERSION_LESS_THAN_OR_EQUAL_TO_W_orH(SCREEN_HEIGHT, @"568.0")) {
            POPBasicAnimation *anim = [POPBasicAnimation animationWithPropertyNamed:kPOPViewFrame];
            anim.toValue  =  [NSValue valueWithCGRect:CGRectMake(0, 64, self.view.frame.size.width, self.view.frame.size.height)];
            anim.beginTime = CACurrentMediaTime() +0.1;
            [self.view pop_addAnimation:anim forKey:@"viewAnim"];
        }
     [_iphoneNum resignFirstResponder];
}



// 选择国家区号
- (IBAction)clickArea:(UIButton*)sender
{
    [self resignRespondersForText];
    SectionsViewController* country2 = [[SectionsViewController alloc] init];
    country2.delegate = self;
    [country2 setareaArray:_areaArray];
    [self.navigationController pushViewController:country2 animated:YES];

}


#pragma mark - SecondViewControllerDelegate的方法
- (void)setSecondData:(NSDictionary*)data
{
    self.areaName.text = [NSString stringWithFormat:@"%@", [data objectForKey:@"countryName"]];
    self.areaCode.text = [NSString stringWithFormat:@"+%@", [data objectForKey:@"areaCode"]];
}


-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    
    [self.iphoneNum resignFirstResponder];
    
    
    
}

@end
